package com.baor.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.DeliveryRecordDao;
import com.baor.dao.EquipmentDao;

import com.baor.dao.Removal_recordDao;
import com.baor.domain.*;
import com.baor.service.EquipmentService;
import com.baor.util.R;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class EquipmentServiceImpl implements EquipmentService {
    @Autowired
    private EquipmentDao equipmentDao;

    @Autowired
    private Removal_recordDao removalRecordDao;

    @Autowired
    private DeliveryRecordDao deliveryRecordDao;

    @Override
    public R getList(Map<String, Object> params) {
        // 获取分页参数，如果为空则设置默认值
        Integer pageIndex = (Integer) params.get("pageIndex");
        Integer pageSize = (Integer) params.get("pageSize");
        // 如果pageIndex为null，则设置默认值为1（第一页）
        if (pageIndex == null) {
            pageIndex = 1;
        }
        // 如果pageSize为null，则设置默认值为10（每页10条）
        if (pageSize == null) {
            pageSize = 10;
        }
   
        Page<Equipment> page = new Page<>();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);
        // 第一步：查询设备基本信息
        MPJLambdaWrapper<Equipment> wrapper = new MPJLambdaWrapper<>(Equipment.class)
                .select(Equipment::getId,
                        Equipment::getCode,
                        Equipment::getAddress,
                        Equipment::getNowWeight,
                        Equipment::getStorageStatus,
                        Equipment::getStatus,
                        Equipment::getIsStatus);
        String address = (String) params.get("address");
        if (address != null && !address.equals("")) {
            wrapper.like(Equipment::getAddress, address);
        }
        String code = (String) params.get("code");
        if (code != null && !code.equals("")) {
            wrapper.like(Equipment::getCode, code);
        }
        Integer isStatus = (Integer) params.get("isStatus");
        if (isStatus != null ) {
            wrapper.eq(Equipment::getIsStatus, isStatus);
        }
        Integer storageStatus =(Integer)  params.get("storageStatus");
        if (storageStatus != null ) {
            wrapper.eq(Equipment::getStorageStatus, storageStatus);
        }
        Page<Equipment> equipmentPage = equipmentDao.selectPage(page, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("totalSize", equipmentPage.getTotal());
        map.put("list", equipmentPage.getRecords());
        return R.ok(map);
    }
    @Override
    public R getInfo(Integer id) {
        // 查询设备基本信息
        MPJLambdaWrapper<Equipment> wrapper = new MPJLambdaWrapper<>(Equipment.class)
                .selectAll(Equipment.class)
                .leftJoin(EquipmentHolder.class, EquipmentHolder::getEquipmentId, Equipment::getId)
                .select(CustomerVO::getRealname, CustomerVO::getPhone)
                .leftJoin(CustomerVO.class, CustomerVO::getId, EquipmentHolder::getCustomerId)
                .eq(Equipment::getId, id)
                .eq(Equipment::getIsDeleted, 0);
        MPJLambdaWrapper<DeliveryRecordVO> wrapper2 = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                .select(DeliveryRecordVO::getId)
                .eq(DeliveryRecordVO::getEquipmentId, id);
        Long num= this.deliveryRecordDao.selectCount(wrapper2);
        ExceptionManagerVO vo = equipmentDao.selectJoinOne(ExceptionManagerVO.class, wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("list", vo);
        if (num !=null){
            map.put("num", num);
        }else {
            map.put("num", 0);
        }

        return R.ok(map);
    }


    //TODO id为设备Id
    @Override
    public R getRemovalInfo(Integer id) {
        MPJLambdaWrapper<RemovalRecordVO> wrapper = new MPJLambdaWrapper<>(RemovalRecordVO.class)
                .selectAll(RemovalRecordVO.class)
                .select(Equipment::getCode, Equipment::getAddress)
                .leftJoin(Equipment.class, Equipment::getId, RemovalRecordVO::getEquipmentId)
                .select(UserVO::getUsername,UserVO::getPhone)
                .leftJoin(UserVO.class, UserVO::getId, RemovalRecordVO::getWorkerId)
                .eq(RemovalRecordVO::getEquipmentId, id)
                .orderByDesc(RemovalRecordVO::getRemovalTime) // 按清运时间倒序
                .last("LIMIT 1");;
        MPJLambdaWrapper<DeliveryRecordVO> wrapper2 = new MPJLambdaWrapper<>(DeliveryRecordVO.class)
                .select(DeliveryRecordVO::getId)
                .eq(DeliveryRecordVO::getEquipmentId, id);
        Long num= this.deliveryRecordDao.selectCount(wrapper2);
        RemovalEquipmentVO vo = removalRecordDao.selectJoinOne(RemovalEquipmentVO.class, wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("list", vo);
        if (num !=null){
            map.put("num", num);
        }else {
            map.put("num", 0);
        }
        return R.ok(map);
    }
    @Override
    public R selectFullyEquipment() {
        MPJLambdaWrapper<Equipment> wrapper = new MPJLambdaWrapper<>(Equipment.class)
                .select(Equipment::getId,
                        Equipment::getAddress,
                        Equipment::getIsStatus,
                        Equipment::getCode,
                        Equipment::getNowWeight,
                        Equipment::getLastUseTime
                )
                .eq(Equipment::getStorageStatus, 1)
                .orderByDesc(Equipment::getLastUseTime);


        List<Map<String, Object>> records = equipmentDao.selectJoinMaps(wrapper);
        List<Map<String, Object>> resultList = records.stream()
                .map(this::convertToFrontendFormat)
                .collect(Collectors.toList());
        Map<String, Object> result = new HashMap<>();
        result.put("list", resultList);
        return R.ok(result);
    }

    @Override
    public R update(Map<String, Object> params) {
        // 获取设备ID
        Integer equipmentId = (Integer) params.get("id");
        if (equipmentId == null) {
            return R.er("设备ID不能为空");
        }

        // 查询设备是否存在
        Equipment existingEquipment = equipmentDao.selectById(equipmentId);
        if (existingEquipment == null) {
            return R.er("设备不存在");
        }

        // 更新设备基本信息
        Equipment equipment = new Equipment();
        equipment.setId(equipmentId);
        equipment.setStatus((Integer) params.get("status"));
        equipment.setStorageStatus((Integer) params.get("storageStatus"));
        int i = equipmentDao.updateById(equipment);
        return i > 0 ? R.ok() : R.er();
    }

    private Map<String, Object> convertToFrontendFormat(Map<String, Object> record) {
        Map<String, Object> item = new HashMap<>();
        item.put("equipmentId", record.get("id"));           // 记录ID
        item.put("address", record.get("address")); // 投递时间
        item.put("is_status", record.get("is_status"));         // 投递重量
        item.put("code", record.get("code")); // 设备地址
        item.put("now_weight", record.get("now_weight")+"kg");
        item.put("last_use_time", record.get("last_use_time"));
        return item;
    }
}
